from datetime import datetime, timedelta

from flask import Blueprint, request, jsonify, send_from_directory
from sqlalchemy import func, Integer
from extension import db
from views.auth import admin_required, jwt_required
from module import Task

count_bp = Blueprint('support', __name__)


@count_bp.route('/count_number', methods=['GET'])
@jwt_required()
@admin_required
def count_number():

    today = datetime.now().date()
    yesterday = today - timedelta(days=1)
    # one_week_ago = today - timedelta(days=7)

    # 统计过去一周每天的记录数量
    # daily_counts = db.session.query(
    #     func.date(Task.starttime).label('date'),
    #     func.count(Task.tid).label('count')
    # ).filter(
    #     func.date(Task.starttime) >= one_week_ago,
    #     func.date(Task.starttime) <= today
    # ).group_by(
    #     func.date(Task.starttime)
    # ).all()

    # 统计当天每两个小时的记录数量
    two_hour_counts_today = db.session.query(
        (func.floor(func.hour(Task.starttime) / 2)).label('hour_block'),
        func.count(Task.tid).label('count')
    ).filter(
        func.date(Task.starttime) == today
    ).group_by(
        func.floor(func.hour(Task.starttime) / 2)
    ).all()

    two_hour_counts_yesterday = db.session.query(
        (func.floor(func.hour(Task.starttime) / 2)).label('hour_block'),
        func.count(Task.tid).label('count')
    ).filter(
        func.date(Task.starttime) == yesterday
    ).group_by(
        func.floor(func.hour(Task.starttime) / 2)
    ).all()


    return jsonify({
        'two_hour_counts_yesterday': {f'{hour * 2}-{hour * 2 + 1}': count for hour, count in two_hour_counts_yesterday},
        'two_hour_counts_today': {f'{hour * 2}-{hour * 2 + 1}': count for hour, count in two_hour_counts_today}
    })
